import requests
import json
import datetime, time


class lst:
    # 传入用户
    def __init__(self, user):
        self.user = user

    def log(self, us, time):
        now = datetime.datetime.now()
        data = now.strftime("%m-%d")
        file_handle = open(data + ".txt", mode='a', encoding='utf-8')
        js = json.dumps({"name": us, "time": time})
        file_handle.writelines(js + '\n')
        file_handle.close()

    # 计算用户最近查费状况
    def vos_fee(self):
        url = 'http://vosIP/external/server/GetPayHistory'
        threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days=30))
        threeDayAgo1 = (datetime.datetime.now() - datetime.timedelta())

        body = {
            "account": str(self.user),
            "beginTime": str(threeDayAgo.strftime("%Y%m%d%H%M%S")),
            "endTime": str(threeDayAgo1.strftime("%Y%m%d%H%M%S"))
        }

        js = json.dumps(body)
        re = requests.post(url, data=js).content.decode()
        conunt = json.loads(re)
        # print(conunt)
        if len(conunt['infoPayHistorys']) > 0:
            return conunt['infoPayHistorys'][-1]['fee']
        else:
            return 0

    # 查询客户当前用户余额何透支
    def vos_account(self):
        url = 'http://vosIP/external/server/GetCustomer'

        body = {
            "accounts": [str(self.user)],
        }
        js = json.dumps(body)
        re = requests.post(url, data=js).content.decode()
        conunt1 = json.loads(re)
        
        return conunt1

    def percentage(self):
        def dingtalk_warning(message):
            webhook = "https://oapi.dingtalk.com/robot/send?access_token=钉钉自己的token"
            headers = {'Content-Type': 'application/json'}
            data = {
                "msgtype": "text",
                "text": {
                    "content": message,
                },
            }
            x = requests.post(url=webhook, data=json.dumps(data), headers=headers)
            # print(x.content.decode())
            if x.json()["errcode"] == 0:
                return True
            else:
                return False

        t = time.time()
        tm = int(round(t * 1000))
        threeDayAgo1 = (datetime.datetime.now() - datetime.timedelta())
        account = self.vos_account()
        todayConsumption = account['infoCustomers'][0]['todayConsumption']  # 今日消费
        name = account['infoCustomers'][0]["name"]  # 账户名称
        # vos 账户余额
        money = account['infoCustomers'][0]['money']
        # print(money)
        # vos 账户透支
        limitMoney = account['infoCustomers'][0]['limitMoney']
        account = account['infoCustomers'][0]['account']  # 账户号码
        if int(todayConsumption) > 0:  # 判断用户的今日消费状况
            # 百分之10 计算
            if money < 0:
                shu = limitMoney * 0.9
                # print(shu)
                # 判断金额低于是不是百分之10
                if int(money) > int(-shu):
                    pass
                else:
                    # vos_b = (int(limitMoney) - int(abs(money))) / int(limitMoney) * 100
                    vos_b = int(abs(money)) / int(limitMoney) * 100

                    vos_conunt1 = "客户透支报警" + "\n" + "账户号码：" + str(account) + "\n" + "账户名称：" + str(
                        name) + "\n" + "账户余额：" + str(
                        '%.3f' % money) + "\n" + "今日消费：" + str(round(todayConsumption, 2)) + "\n" + "账户透支：" + str(
                        limitMoney) + "\n" + "设定比例：10%" + "\n" + "剩余比例：" + str(round(100 - vos_b, 2)) + '%'
                    print(vos_conunt1)
                    dingtalk_warning(vos_conunt1)
                    self.log(self.user, tm)
            elif money > 0:
                value = self.vos_fee()
                shu = value * 0.1
                if int(money) < shu:
                    print(1)
                    vos_b = int(money) / int(value) * 100
                    vos_conunt1 = "客户余额报警" + "\n" + "账户号码：" + str(account) + "\n" + "账户名称：" + str(
                        name) + "\n" + "账户余额：" + str(
                        '%.3f' % money) + "\n" + "上次充值：" + str(value) + "\n" + "今日消费：" + str(
                        round(todayConsumption, 2)) + "\n" + "账户透支：" + str(
                        limitMoney) + "\n" + "设定比例：10%" + "\n" + "剩余比例：" + str(
                        round(100 - vos_b, 2)) + '%' + "\n" + "当前时间：" + threeDayAgo1.strftime("%Y-%m-%d %H:%M:%S")
                    print(vos_conunt1)
                    dingtalk_warning(vos_conunt1)
                    self.log(self.user, tm)
                else:
                    print(2)
                    vos_b = int(money) / int(value) * 100

                    vos_conunt1 = "客户余额报警" + "\n" + "账户号码：" + str(account) + "\n" + "账户名称：" + str(
                        name) + "\n" + "账户余额：" + str(
                        '%.3f' % money) + "\n" + "上次充值：" + str(value) + "\n" + "今日消费：" + str(
                        round(todayConsumption, 2)) + "\n" + "账户透支：" + str(
                        limitMoney) + "\n" + "设定比例：10%" + "\n" + "剩余比例：" + str(
                        round(100 - vos_b, 2)) + '%' + "\n" + "当前时间：" + threeDayAgo1.strftime("%m-%d %H:%M:%S")
                    print(vos_conunt1)
                    dingtalk_warning(vos_conunt1)
                    self.log(self.user, tm)
            elif money == 0:
                pass
        else:
            pass


if __name__ == '__main__':
    lsit = lst("")
    lsit.percentage()
